axios.defaults.baseURL='http://ajax-base-api-t.itheima.net';
const tb= document.querySelector('#tb');
const add = document.querySelector('#btnAdd');
const form = document.querySelector('form');
function render(){
    axios({
        url:'/api/getbooks',
        method:'GET'
    }).then(({data:res})=>{
        // console.log(res);
        const renderList = res.data.map(item=>{
            return`<tr>
            <td>${item.id}</td>
            <td>${item.bookname}</td>
            <td>${item.author}</td>
            <td>${item.publisher}</td>
            <td><a href="#" data-id:${item.id}>删除</a></td>
          </tr>`
        }).join('')
        tb.innerHTML=renderList
    })
}
render()
const bookname = document.querySelector('.input-group-addon');
form.addEventListener('click',function(e){
    e.preventDefault()
    console.log(e.target.dataset.name);
    if(e.target.dataset.name==='add'){
        const data = serialize(form,{hash:true})
    axios.post('/api/addbook',data).then(({data:res})=>{
        alert(res.msg)
        console.log(res);
        if(res.status!==201) return 
        this.reset()
        render()
    })  
    }else if(e.target.dataset.name==='sel'){
        e.preventDefault()
        const params = serialize(form,{hash:true})
        console.log(params);
        axios.get('/api/getbooks',params).then(({data:res})=>{
            const {data}=res
            console.log(data);
          const r=  data.filter(item=>{
                if (item.bookname===params.bookname||item.publisher===params.publisher||item.author===params.author) {
                    return item
                }
            }).map(item=>{
                return`<tr>
                <td>${item.id}</td>
                <td>${item.bookname}</td>
                <td>${item.author}</td>
                <td>${item.publisher}</td>
                <td><a href="#" data-id:${item.id}>删除</a></td>
              </tr>`
            }).join('')
          
            console.log(r);
            tb.innerHTML=r
        })

    }
     
})
tb.addEventListener('click',function(e){
   if(e.target.tagName==='A'){
    const id = e.target.dataset.id
    
    axios.get('/api/delbook?id='+id).then(({data:res})=>render())
   }
})